<?php


namespace app\api\controller;

use addons\shopro\model\Store;
use addons\shopro\model\UserServe;
use app\admin\model\ShoproStore;
use app\admin\model\ShoproStoreProject;
use app\admin\model\ShoproStoreWaiter;
use app\api\model\GoodsServeModel;
use app\api\model\LogModel;
use app\api\model\SendgoodsModel;
use app\api\model\SendgoodsServiceModel;
use app\common\controller\Api;
use think\Db;

class Sendgoods extends Api
{
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['test', 'test1'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    public function shop()
    {
        $data = ShoproStore::where("status","1")
            ->whereNull('deletetime')
            ->field('id,name')
            ->select();
        $this->success('成功',$data);
    }

    //服务礼遇券
    public function serve()
    {
        UserServe::delServe();
        $user_id = $this->auth->id;
        $map = [
            'user_id'=>$user_id,
            'serve_num' => ['>',0]
        ];
        $status = input('status');
        $count = 0;
        if($status == 1){  //处理已使用的逻辑
            $smap = [
                'user_id'=>$user_id,
                'state' => ['in',[1,2]],
            ];
            $use = GoodsServeModel::where($smap)->select();
            $count = count($use);
            $ids = array_column($use,'serve_id');
            $ids = array_unique($ids);
            $map = [
                'user_id'=>$user_id,
            ];
            if(!empty($ids)){
                $map += [
                    'id' => ['in', $ids],
                ];
            }
        }
        if($status == 2){
            $list = Db::table('fa_shopro_user_coupons_serve_overdue')
                ->where("user_id",$user_id)
                ->select();
            $ids = array_column($list,'serve_id');
            $ids = array_unique($ids);
            $map = [
                'user_id'=>$user_id,
            ];
            if(!empty($ids)){
                $map += [
                    'id' => ['in', $ids],
                ];
            }
        }
        $data = UserServe::where($map)->select();
        $data = collection($data)->toArray();

        foreach ($data as &$v){
            if($v['expiretime']){
                $v['desc'] = '服务预约使用 '.date('Y-m-d H:i:s',$v['expiretime']).' 过期提示';
            }else{
                $val['desc'] = '服务预约使用';
            }
            $v['expiretime_text'] = date('Y-m-d H:i:s',$v['expiretime']);
            if($status == 1){
                $smap = [
                    'user_id'=>$user_id,
                    "serve_id" => $v['id'],
                ];
                $count = GoodsServeModel::where($smap)->count();
                $v['serve_num'] = $count;
                $v['desc'] = '已使用';
            }
            if($status == 2){
                $map = [
                    "user_id" => $user_id,
                    "serve_id" => $v['id'],
                ];
                $count = Db::table('fa_shopro_user_coupons_serve_overdue')->where($map)->sum('serve_num');
                $v['serve_num'] = $count;
                $v['desc'] = '已过期';
            }
        }
        $this->success('成功',$data);
    }

    //添加预约
    public function addserve()
    {
        $user = $this->auth->getUser();
        $input = input();
        if(empty($input['shop_id'])){
             $this->error('shop_id必传');
        }
        if(empty($input['serve_id'])){
            $this->error('serve_id必传');
        }
        if(empty($input['username'])){
            $this->error('username必传');
        }
        if(empty($input['mobile'])){
            $this->error('mobile必传');
        }
        if(empty($input['serve_time'])){
            $this->error('serve_time必传');
        }

        $input['serve_time'] = strtotime($input['serve_time']);
        if(!empty($input['id'])){
            $model = new GoodsServeModel();
            $input['state'] = 1;
            $model->allowField(true)->save($input,['id'=>$input['id']]);
            $this->success('修改成功','');
        }
        $map = [
            'user_id' => $user['id'],
            'shop_id' => $input['shop_id'],
            'state' => 1,
        ];
        $row = GoodsServeModel::where($map)->find();
        if($row){
             $this->error('您已预约');
        }
        $serve = UserServe::get($input['serve_id']);
        if(empty($serve) || $serve['serve_num'] <= 0){
             $this->error('没有服务券，无法预约');
        }
        $serve->serve_num -= 1;
        $serve->save();

        /*$serve = UserServe::get($input['serve_id']);
        if(empty($serve) || $serve['serve_num'] <= 0){
            $this->error('没有服务券，无法预约');
        }*/
        $input['user_id'] = $user['id'];
        $model = new GoodsServeModel($input);
        $model->allowField(true)->save();


        $this->success('预约成功','');
    }

    public function editserve()
    {
        $data = GoodsServeModel::get(input('id'));
    }

    //预约记录
    public function serveindex()
    {
        $user = $this->auth->getUser();
        $map = [
            'user_id' => $user['id'],
            //'serve_id' => input('serve_id'),
        ];
        $status = (int)input('status');
        if($status == 0){
            $map += [
                "state" => 1,
            ];
        }
        if($status == 1){
            $map += [
                "state" => 2,
                "is_commet" => 0,
            ];
        }
        if($status == 2){
            $map += [
                "state" => 2,
                "is_commet" => 1,
            ];
        }
        $list = GoodsServeModel::where($map)->paginate()->toArray();
        foreach($list['data'] as &$v){
            if(!empty($v['commet_time'])){
                $v['commet_time_text'] = date('Y-m-d H:i:s',$v['commet_time']);
            }else{
                $v['commet_time_text'] = '';
            }
        }
        $this->success('成功',$list);
    }

    public function usercommet()
    {
        $id = input('id');
        if(empty($id)){
             $this->error('id必传');
        }
        $commet = input('commet');
        if(empty($commet)){
             $this->error('commet 必传');
        }
        $model = GoodsServeModel::get($id);
        if(empty($model)){
             $this->error('id错误');
        }
        $model->is_commet = 1;
        $model->commet_time = time();
        $model->commet = $commet;
        $model->save();
        $this->success('提交成功','');
    }

    //预约详情
    public function serveDetail()
    {
        $data = GoodsServeModel::get(input('id'));
        $this->success('成功',$data);
    }

    //取消预约
    public function delserve()
    {
        $data = GoodsServeModel::get(input('id'));
        if($data){
            $data->state = 0;
            $data->save();
            $row = UserServe::get($data['serve_id']);
            if($row){
                $row->serve_num += 1;
                $row->save();
            }
        }
        $this->success('取消成功','');
    }


    public function lists()
    {
        $type_id = input('type_id');
        $user = $this->auth->getUser();
        if(empty($type_id)){
            $type_id = 2;
        }
        $map = [
            'user_id'=>$user['id'],
            'sendtype_id' => $type_id,
        ];
        $list = SendgoodsModel::where($map)->paginate()->toArray();
        foreach ($list['data'] as &$val){
            $val['num'] = 1;
            if(empty($val['image'])){
                $val['image'] = 'https://oss.bigchun.com/fangzhiyuan/uploads/20221029/54d2a63df0d13e7d9481ab8ecaaab15c.png';
             $val['title'] = '入会礼遇';
            }
        }
        $this->success('成功',$list);
    }

    public function detail()
    {
        $id = input('id');
        $model = SendgoodsModel::get($id);
        if($model){
            $model['wuliu_list'] = [];
        }
        $this->success('成功',$model);
    }

    public function shengri()
    {
        $list = [
            ['id' => '' ,'title' => '礼遇优惠券','num' => 1,'createtime_text' => date('Y-m-d'),'status' => 0],
            ['id' => '' ,'title' => '礼遇优惠券','num' => 1,'createtime_text' => date('Y-m-d'),'status' => 0],
            ['id' => '' ,'title' => '礼遇优惠券','num' => 2,'createtime_text' => date('Y-m-d'),'status' => 1],
        ];
        $list = [];
        $this->success('成功',$list);
    }

    // 服务礼遇列表
    function service_lists()
    {
        $user = $this->auth->getUser();
        $where = [
            'user_id'=>$user->id,
        ];
        $list = SendgoodsServiceModel::where($where)->paginate()->toArray();
        foreach ($list['data'] as &$val){
            $val['num'] = 1;
        }
        $this->success('成功',$list);
    }

    // 礼遇详情
    public function service_detail($id = null)
    {
        if (!$id) {
            $id = $this->request->get('id');
        }
        if (!$id) {
            $this->error('缺少参数');
        }
        $userInfo = $this->auth->getUser();
        $service = SendgoodsServiceModel::where(['id' => $id, 'user_id' => $userInfo->id])->find();
        if (empty($service)) {
            $this->error('礼遇不存在');
        }
        $store_id = $service->shopro_store_id ?? 0;
        $shopro_store_project_id = $service->shopro_store_project_id ?? 0;
        $shopro_store_waiter_id = $service->shopro_store_waiter_id ?? 0;

        $storeInfo = Store::where(['status' => 1, 'id' => $store_id])->find();
        $project_name = ShoproStoreProject::where(['id' => $shopro_store_project_id])->value('name') ?? '';
        $waiter_name = ShoproStoreWaiter::where(['id' => $shopro_store_waiter_id])->value('name') ?? '';

        $service->store_name = $storeInfo->name ?? '';
        $service->store_province_name = $storeInfo->province_name ?? '';
        $service->store_city_name = $storeInfo->city_name ?? '';
        $service->store_area_name = $storeInfo->area_name ?? '';
        $service->project_name = $project_name;
        $service->waiter_name = $waiter_name;
        $service->nickname = $userInfo->nickname ?? '';
        //TODO: 核销二维码生成
        $service->qrcode = 'https://d-fangzhi.bigchun.com/assets/img/connect.png';

        $this->success('成功', $service);
    }

    // 服务预约
    public function service_reserve()
    {
        $params = $this->request->param();
        $data = SendgoodsServiceModel::reserve($params);
        $this->success('礼遇预约', $data);
    }
}
